﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace NTrace.VSPackage
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the 
    /// IVsPackage interface and uses the registration attributes defined in the framework to 
    /// register itself and its components with the shell.
    /// </summary>
    // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
    // a package.
    [PackageRegistration(RegisterUsing = RegistrationMethod.CodeBase, UseManagedResourcesOnly = true)]
    // This attribute is used to register the informations needed to show the this package
    // in the Help/About dialog of Visual Studio.
    [InstalledProductRegistration(
#if !NET40
        true,
#endif
        "#110", 
        "#112", 
        "2.0", 
        IconResourceID = 400)]
    // In order be loaded inside Visual Studio in a machine that has not the VS SDK installed, 
    // package needs to have a valid load key (it can be requested at 
    // http://msdn.microsoft.com/vstudio/extend/). This attribute tells the shell that this 
    // package has a load key embedded in its resources with ID '120'.
    [ProvideLoadKey(
      "Standard",
      "2.0",
      "NTrace",
      "HopperSoft",
      120)]
    // The configuration-independent property page for setting NTrace options
    [ProvideObject(typeof(NTracePropertyPage), RegisterUsing = RegistrationMethod.CodeBase)]
    [Guid(GuidList.GuidNTracePackageString)]
    [ProvideProjectFactory(
      typeof(NTraceConsoleProjectFactory),
      "Instrumented Console Project",
      "Instrumented Project Files (*.csproj);*.csproj",
      "csproj",
      "csproj",
      NTracePackage.NullTemplatePath,
      LanguageVsTemplate = "CSharp",
      NewProjectRequireNewFolderVsTemplate = true)]
    [ProvideProjectFactory(
      typeof(NTraceLibraryProjectFactory),
      "Instrumented Library Project",
      "Instrumented Project Files (*.csproj);*.csproj",
      "csproj",
      "csproj",
      NTracePackage.NullTemplatePath,
      LanguageVsTemplate = "CSharp",
      NewProjectRequireNewFolderVsTemplate = true)]
    [ProvideProjectFactory(
      typeof(NTraceWinFormsProjectFactory),
      "Instrumented WinForms Project",
      "Instrumented Project Files (*.csproj);*.csproj",
      "csproj",
      "csproj",
      NTracePackage.NullTemplatePath,
      LanguageVsTemplate = "CSharp",
      NewProjectRequireNewFolderVsTemplate = true)]
    public sealed class NTracePackage : Package, IVsInstalledProduct
    {
        internal const String NullTemplatePath = "\\..\\NullPath";
        /// <summary>
        /// Default constructor of the package.
        /// Inside this method you can place any initialization code that does not require 
        /// any Visual Studio service because at this point the package object is created but 
        /// not sited yet inside Visual Studio environment. The place to do all the other 
        /// initialization is the Initialize method.
        /// </summary>
        public NTracePackage()
        {
            EtwTrace.Trace(EtwTraceLevel.Verbose, EtwTraceFlag.StackTracing, "NTracePackage::ctor");
        }

        /////////////////////////////////////////////////////////////////////////////
        // Overriden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            EtwTrace.Trace(EtwTraceLevel.Verbose, EtwTraceFlag.StackTracing, "NTracePackage::Initialize");
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();
            
            this.RegisterProjectFactories();
        }

        /// <summary>
        /// Registers the project factories provided by this VSPackage
        /// </summary>
        /// <remarks>
        /// We need to register any project factories with VS or we will get the dreaded
        /// 'The project type is not supported by this installation' load error.
        /// </remarks>
        private void RegisterProjectFactories()
        {
            EtwTrace.Trace(EtwTraceLevel.Verbose, EtwTraceFlag.StackTracing, "NTracePackage::RegisterProjectFactories - enter ");
            base.RegisterProjectFactory(new NTraceConsoleProjectFactory(this));
            base.RegisterProjectFactory(new NTraceLibraryProjectFactory(this));
            base.RegisterProjectFactory(new NTraceWinFormsProjectFactory(this));
            EtwTrace.Trace(EtwTraceLevel.Verbose, EtwTraceFlag.StackTracing, "NTracePackage::RegisterProjectFactories - exit");
        }
        #endregion

        #region IVsInstalledProduct Members
        int IVsInstalledProduct.IdBmpSplash(out uint pIdBmp)
        {
            pIdBmp = 300;
            return Microsoft.VisualStudio.VSConstants.S_OK;
        }

        int IVsInstalledProduct.IdIcoLogoForAboutbox(out uint pIdIco)
        {
            pIdIco = 400;
            return Microsoft.VisualStudio.VSConstants.S_OK;
        }

        int IVsInstalledProduct.OfficialName(out string pbstrName)
        {
            pbstrName = this.GetResourceString("110");
            return Microsoft.VisualStudio.VSConstants.S_OK;
        }

        int IVsInstalledProduct.ProductDetails(out string pbstrProductDetails)
        {
            pbstrProductDetails = this.GetResourceString("112");
            return Microsoft.VisualStudio.VSConstants.S_OK;
        }

        int IVsInstalledProduct.ProductID(out string pbstrPID)
        {
            pbstrPID = this.GetResourceString("111");
            return Microsoft.VisualStudio.VSConstants.S_OK;
        }
        #endregion

        private string GetResourceString(string resourceName)
        {
            string resourceValue;
            IVsResourceManager resourceManager =
                (IVsResourceManager)GetService(typeof(SVsResourceManager));
            if (resourceManager == null)
            {
                throw new InvalidOperationException("Could not get SVsResourceManager service. Make sure that the package is sited before calling this method");
            }
            Guid packageGuid = this.GetType().GUID;
            int hr = resourceManager.LoadResourceString(
                ref packageGuid, -1, resourceName, out resourceValue);
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hr);
            return resourceValue;
        }
    }
}
